package com.kuqi;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.kuqi.core.AppActivity;
import com.kuqi.core.ApplicationPersistent;
import com.kuqi.entitiy.UserInfo;
import com.kuqi.http.HttpCmd;
import com.kuqi.http.HttpResponse;
import com.kuqi.utils.JsonUtil;
import com.kuqi.utils.UrlTool;

import java.util.Timer;
import java.util.TimerTask;


public class LoginActivity extends AppActivity implements View.OnClickListener {

    // 主动登录回调命令的handle——key
    public static final int HANDLER_KEY_LOGIN_PAGE = 123001;

    // 登录成功回调命令的handle——key
    public static final int HANDLER_KEY_LOGIN_SUCCESS = 123002;

    // 用于命令发送的本类Handle, 通用HTTP回调和presenter回调， http在持久层ApplicationPersistent
    private Handler msgHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == HANDLER_KEY_LOGIN_PAGE){ // 本页面的登录命令
                HttpResponse loginResult = JsonUtil.getInstance().fromJson(msg.obj.toString(), HttpResponse.class);
                switch(loginResult.getCode()) {
                    case 200:
                        Log.e("LoginActivity", "success！");
                        // 登录成功时要将用户信息储存，避免重复输入登录
                        String dats = loginResult.getData().toString();
                        UserInfo user = JsonUtil.getInstance().fromJson(dats, UserInfo.class);
                        SharedPreferences sharedPreferences = getSharedPreferences("userLogin", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();//获取编辑器
                        editor.putString("applyKey", user.getApplyKey());
                        editor.putString("secretKey", user.getSecretKey());
                        editor.apply();//提交修改
                        // 查询状态置为完成
                        ApplicationPersistent.getApplication().getDataState().setUserInfoState(true);
                        // 用户信息存储在持久层
                        ApplicationPersistent.getApplication().setUserInfo(user);
                        // 开始准备数据并等待数据加载完成的跳转
                        startSearchDataForInit();
                        break;
                    case 400:
                        Log.e("LoginActivity", "fail！");
                        Toast.makeText(getApplicationContext(),"TvT 登录失败,未知异常!",Toast.LENGTH_SHORT).show();
                        login_load_splash.setVisibility(View.GONE);
                        break;
                    case 404:
                        Log.e("LoginActivity", "没有数据！");
                        Toast.makeText(getApplicationContext(),"TvT 登录失败,账号不存在!",Toast.LENGTH_SHORT).show();
                        login_load_splash.setVisibility(View.GONE);
                        break;
                    case 301:
                        Log.e("LoginActivity", "密匙错误！");
                        Toast.makeText(getApplicationContext(),"TvT 登录失败,密匙错误！",Toast.LENGTH_SHORT).show();
                        login_load_splash.setVisibility(View.GONE);
                        break;
                    case 302:
                        Log.e("LoginActivity", "认证过期！");
                        Toast.makeText(getApplicationContext(),"TvT 登录失败,认证过期！",Toast.LENGTH_SHORT).show();
                        login_load_splash.setVisibility(View.GONE);
                        break;
                    case 303:
                        Log.e("LoginActivity", "账号重复！");
                        Toast.makeText(getApplicationContext(),"TvT 账号重复！",Toast.LENGTH_SHORT).show();
                        login_load_splash.setVisibility(View.GONE);
                        break;
                    default:
                        Log.e("LoginActivity", "意料之外的登录状态！");
                        Toast.makeText(getApplicationContext(),"意料之外的登录状态！",Toast.LENGTH_SHORT).show();
                        login_load_splash.setVisibility(View.GONE);
                        break;
                }
            }else if(msg.what == HANDLER_KEY_LOGIN_SUCCESS){
                // 跳转到主界面
                login_load_splash.setVisibility(View.GONE);
                Intent intent= new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }else{ // 源于本地的环命令 ApplicationPersistent.HANDLER_KEY_LOC
                // TODO login界面内容简单，没有用到本地环回调和状态检测，所以这里是空的
            }
        }
    };


    // 一些图像资源
    private ImageView iv_bg;
    private ImageView iv_name;
    private ImageView iv_password;
    private EditText l_username, l_password;
    private TextView forgetSecret;
    private ImageView login_qq, login_wx,login_wb;
    private RelativeLayout login_load_splash;

    // 登录前的延时数据查询
    private Timer dataTimer = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 屏蔽标题栏
        hideActionBar();

        // 绑定显示界面
        setContentView(R.layout.login_page);

        // 初始化控件
        init();
        initFocus();
    }


    /**
     * 为取得的(EditText)对象添加setOnFocusChangeListener()，重写里面的方法。
     */
    private void initFocus() {
        l_password.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View V, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    iv_password.setImageResource(R.drawable.ic_login_pwd_highlighted);
                    iv_bg.setImageResource(R.drawable.ic_login_invisible);
                } else {
                    // 此处为失去焦点时的处理内容
                    iv_password.setImageResource(R.drawable.ic_login_pwd_normal);
                    iv_bg.setImageResource(R.drawable.ic_login_visible);
                }
            }
        });
        l_username.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    iv_name.setImageResource(R.drawable.ic_login_phone_highlighted);
                } else {
                    // 此处为失去焦点时的处理内容
                    iv_name.setImageResource(R.drawable.ic_login_phone_normal);
                }
            }
        });
    }


    /**
     * 初始化,获取各种控件并配置点击监听器
     */
    public void init() {
        l_username = findViewById(R.id.l_username);
        l_password = findViewById(R.id.l_password);
        iv_bg = findViewById(R.id.iv_bg);
        iv_name = findViewById(R.id.iv_name);
        iv_password = findViewById(R.id.iv_password);
        login_load_splash = findViewById(R.id.login_load_splash);

        forgetSecret = findViewById(R.id.l_forgetSecret);
        login_qq = findViewById(R.id.login_qq);
        login_wx = findViewById(R.id.login_wx);
        login_wb = findViewById(R.id.login_wb);
        forgetSecret.setOnClickListener(this);
        login_qq.setOnClickListener(this);
        login_wx.setOnClickListener(this);
        login_wb.setOnClickListener(this);

        ImageView l_backspace = findViewById(R.id.l_backspace);
        Button bt_login = findViewById(R.id.bt_login);
        TextView l_register = findViewById(R.id.l_register);
        l_backspace.setOnClickListener(this);
        bt_login.setOnClickListener(this);
        l_register.setOnClickListener(this);
        ImageView iv_lg_ld_gif = findViewById(R.id.iv_lg_ld_gif);
        Glide.with(this).asGif().load(R.mipmap.login_sp_ld_gif).into(iv_lg_ld_gif);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.l_backspace:
                finish();
                break;
            case R.id.l_forgetSecret:
                Toast.makeText(this,"此功能禁用，如有必要请联系作者白帅.",Toast.LENGTH_SHORT).show();
                break;
            case R.id.bt_login:
                login_load_splash.setVisibility(View.VISIBLE);
                String applyKey = l_username.getText().toString();
                String secretKey = l_password.getText().toString();
                UserInfo user = new UserInfo(applyKey,secretKey);
                String jsonStr = JsonUtil.getInstance().toJson(user);
                //构建Http命令并发送
                HttpCmd cmd = new HttpCmd(msgHandler, jsonStr, UrlTool.URL_LOGIN, HANDLER_KEY_LOGIN_PAGE);
                ApplicationPersistent.getApplication().getFuncWorker().SendHttp(cmd);
                break;
            case R.id.l_register:
                Toast.makeText(this,"当前不允许注册,请联系白帅要注册码.",Toast.LENGTH_SHORT).show();
                break;
            case R.id.login_qq:
                Toast.makeText(this,"某Q不给授权，我也没办法啊（T^T）.",Toast.LENGTH_SHORT).show();
                break;
            case R.id.login_wx:
                Toast.makeText(this,"某信不给授权，我也没办法啊（T^T）.",Toast.LENGTH_SHORT).show();
                break;
            case R.id.login_wb:
                Toast.makeText(this,"某博不给授权，我也没办法啊（T^T）.",Toast.LENGTH_SHORT).show();
                break;
        }
    }



    /**
     * 开始查询初始化程序必须的各种数据
     */
    private void startSearchDataForInit(){
        //启动延时跳转计时器(延时2秒启动, 每秒检测一下数据查询结果)
        dataTimer =new Timer();
        dataTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                dataWorker();
            }
        },2000, 1000);
        // 开始查询主页数据
        ApplicationPersistent.getApplication().searchHomeData();
        // 开始查询书城数据
        ApplicationPersistent.getApplication().searchStoreData();
    }

    /**
     * 计时器检测数据加载情况执行方法
     */
    private void dataWorker(){
        boolean isAllReadyHome = ApplicationPersistent.getApplication().getDataState().checkAllReadyHome();
        boolean isAllReadyStore = ApplicationPersistent.getApplication().getDataState().checkAllReadyStore();
        if(isAllReadyHome && isAllReadyStore){ // 预查已经结束
            dataTimer.cancel();
            msgHandler.sendMessage(msgHandler.obtainMessage(HANDLER_KEY_LOGIN_SUCCESS));
        }else{ // 继续查询
            Log.w("CheckIfReady","数据查询尚未成功！继续等待！");
        }
        Log.w("dataWorker","#############################");
    }


}
